package com.wxy.ej.flow.modules.taskflow.service.nodeExecuteStrategy.strategy.controller;

import com.alibaba.fastjson.JSONObject;
import com.rt.easyjava.common.base.Result;
import com.wxy.ej.flow.modules.taskflow.dto.DataDto;
import com.wxy.ej.flow.modules.taskflow.dto.NodeDto;
import com.wxy.ej.flow.modules.taskflow.service.nodeExecuteStrategy.NodeStrategy;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

@Slf4j
public class ControllerCircleStartNodeStrategy extends NodeStrategy {

    public static final String IsCircleBodyContinueRun_True = "IsCircleBodyContinueRun_True";
    public static final String IsCircleBodyContinueRun_False = "IsCircleBodyContinueRun_False";

    @Override
    public Result action(NodeDto node, JSONObject flowDataJson, DataDto dataDto) throws Exception{
        final String CircleIndexKey = node.getId()+"_currentCircleIndex";
        String defineVarName = node.getDefineVarName();
        dataDto.setInCircle(true);

        // 初始化下标
        Object currentCircleIndexObj = dataDto.getStorageControllerVarMap().get(CircleIndexKey);
        if (currentCircleIndexObj==null) {
            dataDto.getStorageControllerVarMap().put(CircleIndexKey, 0);
        }
        // 当前下标
        int currentCircleIndex = (Integer) dataDto.getStorageControllerVarMap().get(CircleIndexKey);

        // 取值
        Object dataListObj = executeScriptForResult(dataDto, defineVarName);
        List<Map<String, Object>> dataList  = (List<Map<String, Object>>)dataListObj;

        if (dataList==null || dataList.isEmpty()) {
            dataDto.resetCircleInfo(CircleIndexKey, node.getCircleItemVar());
            return Result.builder(IsCircleBodyContinueRun_False);
        }

        // 判断 dataList 里是否有足够数据
        int dataListSize = dataList.size();
        // 循环结束了
        if (dataListSize < currentCircleIndex+1) {
            dataDto.resetCircleInfo(CircleIndexKey, node.getCircleItemVar());
            return Result.builder(IsCircleBodyContinueRun_False);
        }

        // break 结束循环
        if (dataDto.isBreak()) {
            dataDto.resetCircleInfo(CircleIndexKey, node.getCircleItemVar());
            return Result.builder(IsCircleBodyContinueRun_False);
        }

        // continue
        if (dataDto.isContinue()) {
            dataDto.setContinue(false);
        }

        // 取、存item
        Map<String, Object> dataItemMap = dataList.get(currentCircleIndex);
        dataDto.getStorageDataVarMap().put(node.getCircleItemVar(), dataItemMap);
        // 下标自增
        dataDto.getStorageControllerVarMap().put(CircleIndexKey, ++currentCircleIndex);

        return Result.builder(IsCircleBodyContinueRun_True);
    }
}
